package edu.hit.stu.config;

import edu.hit.stu.util.jwt.JwtProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class JWTSecurityContextRepository implements ServerSecurityContextRepository {

    private final JwtProperties jwtProperties;
    private final JWTReactiveAuthenticationManager jwtReactiveAuthenticationManager;

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return null;
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst(jwtProperties.getHeader());
        return jwtReactiveAuthenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(null, token))
                .map(SecurityContextImpl::new);
    }
}
